package com.ktkj.init.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktkj.init.constant.PermissionInfoConstant;
import com.ktkj.init.dto.PermissionInfoCondition;
import com.ktkj.init.dto.PermissionInfoForm;
import com.ktkj.init.entity.PermissionInfo;
import com.ktkj.init.exception.BusinessException;
import com.ktkj.init.mapper.PermissionInfoMapper;
import com.ktkj.init.service.PermissionInfoService;
import com.ktkj.init.service.UserInfoService;
import com.ktkj.init.utils.SpringUtils;
import com.ktkj.init.vo.QueryResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 权限信息表 服务实现类
 * </p>
 *
 * @author ktkj
 * @since 2021-12-31
 */
@Service
public class PermissionInfoServiceImpl extends ServiceImpl<PermissionInfoMapper, PermissionInfo> implements PermissionInfoService {

    @Resource
    private UserInfoService userInfoService;

    @Override
    public QueryResult<PermissionInfo> page(PermissionInfoCondition condition) {
        QueryWrapper<PermissionInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(condition.getPermissionCode())) {
            wrapper.eq("permission_code", condition.getPermissionCode().trim());
        }
        if (StringUtils.isNotBlank(condition.getPermissionName())) {
            wrapper.like("permission_name", condition.getPermissionName().trim());
        }
        if (StringUtils.isNotBlank(condition.getPermissionUrl())) {
            wrapper.like("permission_url", condition.getPermissionUrl().trim());
        }
        if (condition.getParentId() != null) {
            wrapper.eq("parent_id", condition.getParentId());
        }
        wrapper.orderByDesc("create_date");

        List<PermissionInfo> resultData;
        long totalRecord;
        if (condition.getCurrent() != -1) {
            IPage<PermissionInfo> page = page(new Page<>(condition.getCurrent(), condition.getPageSize()), wrapper);
            resultData = page.getRecords();
            totalRecord = page.getTotal();
        } else {
            resultData = list(wrapper);
            totalRecord = resultData.size();
        }
        QueryResult<PermissionInfo> queryResult = new QueryResult<>();
        queryResult.setResultData(resultData);
        queryResult.setTotalRecord(totalRecord);
        return queryResult;
    }

    @Override
    public List<PermissionInfo> treeList() {
        QueryWrapper<PermissionInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", PermissionInfoConstant.HIGHEST_CODE);
        List<PermissionInfo> list = list(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            for (PermissionInfo info : list) {
                this.getChildrenList(info);
            }
        }
        return list;
    }


    public PermissionInfo getChildrenList(PermissionInfo permissionInfo) {
        Long id = permissionInfo.getId();
        QueryWrapper<PermissionInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<PermissionInfo> dataList = list(wrapper);
        if (!CollectionUtils.isEmpty(dataList)) {
            permissionInfo.setChildrenList(dataList);
            for (PermissionInfo bean : dataList) {
                getChildrenList(bean);
            }
        }
        return permissionInfo;
    }

    @Override
    @Transactional
    public PermissionInfo saveOrUpdate(PermissionInfoForm form) {
        PermissionInfo bean = null;
        String errorMsg = "保存失败，请联系管理员！";
        try {
            Long userId = userInfoService.getByUserId();
            PermissionInfo newPermissionInfo = this.getByPermissionCode(form.getPermissionCode().trim());
            if (form.getId() != null) {
                bean = getById(form.getId());
                if (bean == null) {
                    errorMsg = "id错误，没有查询到对应数据！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                if (newPermissionInfo != null && !newPermissionInfo.getPermissionCode().equals(bean.getPermissionCode())) {
                    errorMsg = "权限编号不能重复！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                bean.setUpdateId(userId);
                bean.setUpdateDate(new Date());
            } else {
                if (newPermissionInfo != null) {
                    errorMsg = "权限编号不能重复！";
                    throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
                }
                bean = new PermissionInfo();
                bean.setCreateId(userId);
            }
            SpringUtils.copyPropertiesIgnoreNull(form, bean);
            saveOrUpdate(bean);
        } catch (Exception e) {
            log.error(errorMsg, e);
            throw new BusinessException(BusinessException.BUSSINESS_EXCEPTION, errorMsg);
        }
        return bean;
    }

    public PermissionInfo getByPermissionCode(String permissionCode) {
        PermissionInfo bean = getOne(new QueryWrapper<PermissionInfo>()
                .lambda()
                .eq(PermissionInfo::getPermissionCode, permissionCode));
        return bean;
    }
}
